package cn.peng.stu4teach.util.http;

import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import androidx.annotation.NonNull;

import java.io.IOException;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 基于 OkHttp3 实现的 网络请求工具类
 */
public class HttpUtils {

    /**
     * OkHttpClient 单例实例
     */
    private static final OkHttpClient CLIENT = new OkHttpClient.Builder().build();

    /**
     * 发起GET请求
     *
     * @param url      请求URL
     * @param callback 结果回调
     */
    public static void sendGetRequest (String url, final IHttpRe callback) {
        Request request = new Request.Builder()
                                  .url(url)
                                  .build();

        CLIENT.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure (@NonNull Call pCall, @NonNull IOException pE) {
                handlerPost(null,pE.getMessage(), callback);
            }

            @Override
            public void onResponse (@NonNull Call pCall, @NonNull Response pResponse) throws IOException {
                if (!pResponse.isSuccessful()) {
                    handlerPost(null,"Unexpected code " + pResponse, callback);
                    return;
                }

                final String responseBody = pResponse.body().string();
                handlerPost(responseBody,"请求成功", callback);
            }
        });
    }

    /**
     * 发起POST请求
     *
     * @param url      请求URL
     * @param params   POST参数
     * @param callback 结果回调
     */
    public static void sendPostRequest (String url, final Map<String, String> params, final IHttpRe callback) {
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        for (Map.Entry<String, String> entry : params.entrySet()) {
            builder.addFormDataPart(entry.getKey(), entry.getValue());
        }

        Request request = new Request.Builder()
                                  .url(url)
                                  .post(builder.build())
                                  .build();

        CLIENT.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure (@NonNull Call pCall, @NonNull IOException pE) {
                handlerPost(null,pE.getMessage(), callback);
            }

            @Override
            public void onResponse (@NonNull Call pCall, @NonNull Response pResponse) throws IOException {
                if (!pResponse.isSuccessful()) {
                    handlerPost(null,"Unexpected code " + pResponse, callback);
                    return;
                }

                final String responseBody = pResponse.body().string();
                handlerPost(responseBody, "请求成功",callback);
            }
        });
    }

    /**
     * 使用Handler处理UI线程的回调
     */
    private static void handlerPost (final String result, final String msg, @NonNull final IHttpRe callback) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run () {
                if (TextUtils.isEmpty(result)) {
                    callback.onHttpReError(msg);
                } else {
                    callback.onHttpReSuccess(result);
                }
            }
        });
    }

    // Http 网络请求回调接口
    public interface IHttpRe {
        void onHttpReSuccess (String response);

        void onHttpReError (String errorMessage);
    }
}